package com.alit.face.koala.service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alit.face.koala.entity.KoalaEmpLoyeeEntity;
import com.alit.face.koala.projectvariable.KoalaURI;
import com.litong.utils.http.URLUtil;
import com.litong.utils.http.commonshttpclient.HttpClientUtil;
import com.litong.utils.http.commonshttpclient.HttpConstant;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class FaceKoalaService {
  // 保存不同url的cookies
  public Map<String, String> cookiesMap = new HashMap<>();

  /**
   * 登录并获取cookie，后面所有的接口都需要在请求时带入此cookie,
   * 
   * @param koalaUrl
   * @param username
   * @param password
   * @param isUseCache
   *          是否使用缓存中的用名和密码
   * @return 登陆成功保存cookies,返回登陆成功码,登陆失败不保存cookies,返回登陆失败码,如果登陆成功返回0,调用程序判断,如果返回0,调用cookie
   */
  public int authLogin(String koalaBaseUrl, String username, String password, boolean isUseCache) {
    if (isUseCache) {
      String cookie = cookiesMap.get(koalaBaseUrl);
      if (cookie != null) {
        log.info("从Map中获取cooke成功:" + koalaBaseUrl);
        return 0;
      }
    }
    String url = koalaBaseUrl + KoalaURI.authLogin;
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.setRequestHeader("user-agent", "Koala Admin");
    NameValuePair[] params = { new NameValuePair("username", username), new NameValuePair("password", password) };
    postMethod.setRequestBody(params);
    httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    int statusCode = 0;
    byte[] responseBody = null;

    try {
      statusCode = httpClient.executeMethod(postMethod);
      responseBody = postMethod.getResponseBody();
      if (statusCode != 200) {
        return statusCode;
      }
    } catch (HttpException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      postMethod.releaseConnection();
    }

    String responseString = EncodingUtil.getString(responseBody, "UTF-8");
    JSONObject parseObject = JSON.parseObject(responseString);
    int code = parseObject.getIntValue("code");
    if (code == 0) { // 登陆成功
      log.info("登陆成功");
      // 取出cookies
      Cookie[] cookies = httpClient.getState().getCookies();
      StringBuffer tmpcookies = new StringBuffer();
      for (Cookie c : cookies) {
        tmpcookies.append(c.toString() + ";");
      }
      cookiesMap.put(koalaBaseUrl, tmpcookies.toString());
      return 0;
    } else { // 登陆失败
      return code;
    }
  }

  /**
   * 获取员工信息,
   * 
   * @param koalaUrl
   * @param username
   * @param password
   * @param subject_id
   * @return
   */
  public Map<String, String> getStaffNameByID(String baseURL, String username, String password, int subject_id) {
    log.info(baseURL + "," + username + "," + password + "," + subject_id);
    int loginCode = authLogin(baseURL, username, password, true);
    String cookies = null;
    if (loginCode == 0) {
      cookies = cookiesMap.get(baseURL);
    }
    String url = baseURL + KoalaURI.subject + "/" + subject_id;
    return HttpClientUtil.getWithCookie( url,cookies);
  }

  /**
   * 个人识别照片上传
   * @param koalaBaseUrl
   * @param bytes
   * @return
   */
  public JSONObject subjectPhoto(String koalaBaseUrl, String username, String password, byte[] bytes) {

    int loginCode = authLogin(koalaBaseUrl, username, password, true);
    // 设置cookie
    String cookies = null;
    if (loginCode == 0) {
      cookies = cookiesMap.get(koalaBaseUrl);
    } else {
      log.info("验证失败,请检查原因:" + koalaBaseUrl + "," + username + "," + password);
    }
    StringBuffer append = URLUtil.append(koalaBaseUrl, KoalaURI.photo);
    Map<String, String> uploadBytes = HttpClientUtil.uploadBytes(append.toString(), cookies, "photo", bytes, "",
        "image/jpeg");
    String string = uploadBytes.get(HttpConstant.value);
    JSONObject parseObject = JSON.parseObject(string);
    log.info("上传文件完成:" + append.toString() + ",返回:" + parseObject.toString());
    return parseObject;
  }

  public JSONObject subjectPhoto(String koalaBaseUrl, String username, String password, String filePath) {
    int loginCode = authLogin(koalaBaseUrl, username, password, true);
    // 设置cookie
    String cookies = null;
    if (loginCode == 0) {
      cookies = cookiesMap.get(koalaBaseUrl);
    } else {
      log.info("验证失败,请检查原因:" + koalaBaseUrl + "," + username + "," + password);
    }
    StringBuffer append = URLUtil.append(koalaBaseUrl, KoalaURI.photo);
    File file = new File(filePath);
    Map<String, String> uploadBytes = HttpClientUtil.uploadFile(append.toString(), cookies, "photo", file, filePath,
        "image/jpeg");
    String string = uploadBytes.get(HttpConstant.value);
    JSONObject parseObject = JSON.parseObject(string);
    log.info("上传文件完成:" + append.toString() + ",返回:" + parseObject.toString());
    return parseObject;
  }

  /**
   * 添加用户 
   * @return
   */
  public JSONObject subject(String koalaBaseUrl, String username, String password, KoalaEmpLoyeeEntity employee,
      List<String> photos) {
    int loginCode = authLogin(koalaBaseUrl, username, password, true);
    // 设置cookie
    String cookies = null;
    if (loginCode == 0) {
      cookies = cookiesMap.get(koalaBaseUrl);
    }
    Map<String, String> header = new HashMap<>();
    header.put("cookie", cookies);
    String photoids = JSON.toJSONString(photos);
    StringBuffer append = URLUtil.append(koalaBaseUrl, "/subject");
    Map<String, String> param = new HashMap<>();
    param.put("subject_type", employee.getSubjectType() + "");
    param.put("name", employee.getName());
    param.put("department", employee.getDepartment());
    param.put("title", employee.getTitle());
    param.put("photo_ids", photoids);
    String post = HttpClientUtil.post(append.toString(), header, param);
    JSONObject parseObject = JSON.parseObject(post);
    return parseObject;
  }
}
